package com.tarena.lbs.basic.web.repoistory.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tarena.lbs.base.protocol.pager.BasePageList;
import com.tarena.lbs.basic.web.mapper.BusinessMapper;
import com.tarena.lbs.basic.web.repoistory.BusinessRepository;
import com.tarena.lbs.pojo.basic.bo.BusinessBO;
import com.tarena.lbs.pojo.basic.dos.BusinessDO;
import com.tarena.lbs.pojo.basic.query.BusinessQuery;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;
@Slf4j
@Repository
public class BusinessRepositoryImpl implements BusinessRepository {
    @Autowired
    private BusinessMapper businessMapper;

    @Override
    public BasePageList<BusinessBO> getBusinessListByQuery(BusinessQuery businessQuery) {
        //1. 开启pageHelper 查询动作 必须在开启之后执行,中间不能有任何其他代码逻辑
        PageHelper.startPage(businessQuery.getPageNo(),businessQuery.getPageSize());
        log.debug("p1-批量查询:{}",businessQuery);
        List<BusinessDO> dos=businessMapper.selectBusinessByQuery(businessQuery);
        //2. 使用pagehelper拿到total和转化
        PageInfo<BusinessDO> pageDOS=new PageInfo<>(dos);
        //3. 封装一个BasePageList 需要转化
        //BasePageList<BusinessBO> bos=new BasePageList<>();
        List<BusinessBO> bos=new ArrayList<>();
        if (pageDOS.getTotal()!=0){
            pageDOS.getList().stream().forEach(bDo -> {
                BusinessBO bo=new BusinessBO();
                BeanUtils.copyProperties(bDo,bo);
                bos.add(bo);
            });
        }
        return new BasePageList<>(bos,pageDOS.getTotal());
    }

    @Override
    public Integer save(BusinessBO businessBO) {
        //1.仓储层 BO 转化成DO
        BusinessDO businessDO=new BusinessDO();
        BeanUtils.copyProperties(businessBO,businessDO);
        //2.新增
        log.debug("P2-:仓储{}",businessDO);
        businessMapper.insert(businessDO);
        return businessDO.getId();
    }

    @Override
    public long countBusinessById(Integer businessId) {
        return businessMapper.selectCountById(businessId);
    }

    @Override
    public BusinessBO getBusinessById(Integer id) {
        BusinessDO businessDO = businessMapper.selectBusinessById(id);
        BusinessBO bo=null;
        if (businessDO!=null){
            bo=new BusinessBO();
            BeanUtils.copyProperties(businessDO,bo);
        }
        return bo;
    }
}
